package com.xb.ai.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xb.ai.constant.ErrorMessage;
import com.xb.ai.entity.po.User;
import com.xb.ai.entity.request.UserLayoutRequest;
import com.xb.ai.entity.request.UserLoginRequest;
import com.xb.ai.entity.request.UserRegisterRequest;
import com.xb.ai.common.Result;
import com.xb.ai.entity.vo.UserVo;
import com.xb.ai.exception.BusinessException;
import com.xb.ai.service.IUserService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 用户登录
     * @param userLoginRequest 用户登录请求参数
     * @return 用户信息
     */
    @PostMapping("/login")
    public Result<UserVo> login(@RequestBody UserLoginRequest userLoginRequest) {
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorMessage.PARAMS_ERROR);
        }
        return Result.success(userService.login(userAccount,userPassword));
    }

    /**
     * 用户注册
     * @param userRegisterRequest 用户注册请求参数
     * @return 新用户ID
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody UserRegisterRequest userRegisterRequest) {
        // 参数校验可以放在 Service 层，这里简单校验非空
        if (userRegisterRequest == null || 
            StringUtils.isAnyBlank(userRegisterRequest.getUserAccount(), 
                                     userRegisterRequest.getUserPassword(), 
                                     userRegisterRequest.getCheckPassword())) {
            throw new BusinessException(ErrorMessage.PARAMS_ERROR + ": 注册信息不完整");
        }
        userService.register(userRegisterRequest);
        return Result.success("注册成功");
    }

    /**
     * 用户退出
     * @param userLayoutRequest 用户退出请求参数
     * @return 退出结果
     */
    @PostMapping("/logout")
    public Result<String> logout(@RequestBody UserLayoutRequest userLayoutRequest) {
        Long userId = userLayoutRequest.getUserId();
        User user = userService.getById(userId);
        if (user == null){
            throw new BusinessException(ErrorMessage.USER_NOT_EXIST_ERROR);
        }
        long userLoginId = StpUtil.getLoginIdAsLong();
        if (!userId.equals(userLoginId) || !userId.equals(user.getId())){
            throw new BusinessException(ErrorMessage.NO_AUTH_ERROR);
        }
        StpUtil.logout(userId);
        return Result.success("退出成功");
    }

    /**
     * 判断用户是否登录
     * @return 是否登录
     */
    @PostMapping("/isLogin")
    public Result<Boolean> isLogin() {
        return Result.success(StpUtil.isLogin());
    }

}
